Page({
  data: {
    users: [] as any[],
    filteredUsers: [] as any[],
    loading: false,
    updating: false,
    updatingText: '',
    searchKeyword: '',
    adminCount: 0
  },

  searchTimer: null as any,

  onLoad() {
    this.getUserList()
  },

  onShow() {
    // 页面显示时刷新用户列表
    this.getUserList()
  },

  // 获取用户列表
  async getUserList() {
    this.setData({ loading: true })
    
    try {
      wx.showLoading({
        title: '加载用户列表...'
      })

      const result = await wx.cloud.callFunction({
        name: 'userManager',
        data: {
          action: 'getAllUsers'
        }
      })

      const response = result.result as any
      if (response && response.success) {
        const users = response.data.users || []
        
        // 格式化用户数据
        const formattedUsers = users.map((user: any) => ({
          ...user,
          lastLoginTime: user.lastLoginTime ? this.formatTime(user.lastLoginTime) : '未登录'
        }))
        
        this.setData({
          users: formattedUsers,
          loading: false
        })
        
        // 应用搜索过滤
        this.filterUsers()
        
        console.log('获取用户列表成功:', formattedUsers.length, '个用户')
      } else {
        throw new Error(response?.message || '获取用户列表失败')
      }
    } catch (error: any) {
      console.error('获取用户列表失败:', error)
      wx.showModal({
        title: '加载失败',
        content: '获取用户列表失败：' + (error.message || '网络错误'),
        showCancel: false
      })
      
      this.setData({ loading: false })
    } finally {
      wx.hideLoading()
    }
  },

  // 搜索输入处理
  onSearchInput(e: any) {
    const keyword = e.detail.value
    this.setData({
      searchKeyword: keyword
    })
    
    // 防抖处理
    clearTimeout(this.searchTimer)
    this.searchTimer = setTimeout(() => {
      this.filterUsers()
    }, 300)
  },

  // 过滤用户列表
  filterUsers() {
    const { users, searchKeyword } = this.data
    
    let filteredUsers = users
    
    if (searchKeyword) {
      filteredUsers = users.filter(user => 
        user.nickName.toLowerCase().includes(searchKeyword.toLowerCase())
      )
    }
    
    // 计算管理员数量
    const adminCount = filteredUsers.filter(user => user.isAdmin).length
    
    this.setData({
      filteredUsers,
      adminCount
    })
  },

  // 切换管理员状态
  async toggleAdminStatus(e: any) {
    const { openid, nickname, currentAdmin } = e.currentTarget.dataset
    const newAdminStatus = !currentAdmin
    
    // 确认操作
    const actionText = newAdminStatus ? '设为管理员' : '取消管理员权限'
    const confirmResult = await new Promise<boolean>((resolve) => {
      wx.showModal({
        title: '确认操作',
        content: `确定要将 "${nickname}" ${actionText}吗？`,
        success: (res) => {
          resolve(res.confirm)
        },
        fail: () => {
          resolve(false)
        }
      })
    })
    
    if (!confirmResult) {
      return
    }
    
    // 执行权限更新
    this.setData({ 
      updating: true,
      updatingText: `正在${actionText}...`
    })
    
    try {
      const result = await wx.cloud.callFunction({
        name: 'userManager',
        data: {
          action: 'updateUserAdmin',
          targetOpenId: openid,
          isAdmin: newAdminStatus
        }
      })

      const response = result.result as any
      if (response && response.success) {
        wx.showToast({
          title: response.message || '操作成功',
          icon: 'success'
        })
        
        // 更新本地数据
        const updatedUsers = this.data.users.map(user => {
          if (user.openId === openid) {
            return { ...user, isAdmin: newAdminStatus }
          }
          return user
        })
        
        this.setData({
          users: updatedUsers
        })
        
        // 重新过滤用户列表
        this.filterUsers()
        
        console.log('用户权限更新成功:', nickname, newAdminStatus)
      } else {
        throw new Error(response?.message || '操作失败')
      }
    } catch (error: any) {
      console.error('更新用户权限失败:', error)
      wx.showModal({
        title: '操作失败',
        content: '更新用户权限失败：' + (error.message || '网络错误'),
        showCancel: false
      })
    } finally {
      this.setData({ updating: false })
    }
  },

  // 格式化时间
  formatTime(dateString: string): string {
    if (!dateString) return '未知'
    
    try {
      const date = new Date(dateString)
      const now = new Date()
      const diff = now.getTime() - date.getTime()
      const days = Math.floor(diff / (1000 * 60 * 60 * 24))
      
      if (days === 0) {
        return '今天'
      } else if (days === 1) {
        return '昨天'
      } else if (days < 7) {
        return `${days}天前`
      } else {
        return date.toLocaleDateString()
      }
    } catch (error) {
      return '未知'
    }
  },

  // 返回上一页
  goBack() {
    wx.navigateBack({
      delta: 1
    })
  }
}) 